package yxy.cherry.paycenter.service;

import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import yxy.cherry.paycenter.servlet.order.OrderServlet;

public class OrderService {

	// http 服务器
	private Server httpServer;
	private static OrderService instance;

	public static OrderService getInstance() {
		if (instance == null) {
			instance = new OrderService();
		}
		return instance;
	}

	//http 启动
	public void httpinit(int port) {
		httpServer = new Server();
		HttpConfiguration http_config = new HttpConfiguration();
		final ServerConnector connector = new ServerConnector(httpServer, new HttpConnectionFactory(http_config));
		connector.setPort(port);
		httpServer.addConnector(connector);

		// ----------------------
		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		context.setContextPath("/");
		httpServer.setHandler(context);
		initServlet(context);

		try {
			httpServer.start();
			System.out.println("*********sdk service http start:" + port);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//https 启动
//	public void init(int port) {
//		httpServer = new Server();
//		// -------------------------
//		System.out.println("-----------------------------config.ssl" + Config.SSL);
//		HttpConfiguration https_config = new HttpConfiguration();
//		https_config.setSecureScheme("https");
//
//		final SslContextFactory factory = new SslContextFactory();
//		factory.setKeyStorePath(Config.SSL_JKS_PATH);
//		factory.setKeyStorePassword(Config.SSL_PWD);
//		final ServerConnector connector = new ServerConnector(httpServer, factory,
//				new HttpConnectionFactory(https_config));
//		connector.setPort(port);
//		httpServer.addConnector(connector);
//
//		// ----------------------
//		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
//		context.setContextPath("/");
//		httpServer.setHandler(context);
//		initServlet(context);
//
//		try {
//			httpServer.start();
//			System.out.println("*********sdk service https start:" + port);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	public void stop() {
		if (httpServer != null) {
			try {
				httpServer.stop();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void initServlet(ServletContextHandler context) {
		OrderServlet temp = new OrderServlet();
		context.addServlet(new ServletHolder(temp), "/sdk");
	}

}
